Page({

  /**
   * 页面的初始数据
   */
  data: {
    schema:[
    ],
    zh: '',
    title:'',
    remark: '',
    webUrl: '',
    formData:{
    },
    result: ''
  },
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: options.title,
    })

    this.setData({
      apiType: options.zh,
      title: options.title,
      zh:options.zh,
      remark: options.remark,
      webUrl: options.webUrl
    })
  },
  getFormData(e) {
  },
  /**
 * 将数据复制到AudioBuffer的指定声道
 * @param {AudioBuffer} audioBuffer - 目标音频缓冲区
 * @param {number} channelIndex - 声道索引
 * @param {Float32Array} sourceArray - 源数据数组
 * @param {number} [startInChannel=0] - 声道中开始写入的位置
 * @returns {number} 实际复制的样本数
 */
copyToAudioChannel(audioBuffer, channelIndex, sourceArray, startInChannel = 0) {
  // 验证输入参数
  // if (!(audioBuffer instanceof AudioBuffer)) {
  //     throw new TypeError('第一个参数必须是AudioBuffer实例');
  // }
  
  if (typeof channelIndex !== 'number' || !Number.isInteger(channelIndex) || 
      channelIndex < 0 || channelIndex >= audioBuffer.numberOfChannels) {
      throw new RangeError(`无效的声道索引: ${channelIndex}`);
  }
  
  if (!(sourceArray instanceof Float32Array)) {
      throw new TypeError('源数据必须是Float32Array实例');
  }
  
  if (startInChannel < 0 || startInChannel >= audioBuffer.length) {
      throw new RangeError(`无效的起始位置: ${startInChannel}`);
  }
  
  // 计算可复制的最大长度
  const maxCopyLength = Math.min(
      sourceArray.length, 
      audioBuffer.length - startInChannel
  );
  
  if (maxCopyLength <= 0) {
      console.warn('没有可复制的数据');
      return 0;
  }
  
  // 使用copyToChannel复制数据
  audioBuffer.copyToChannel(sourceArray, channelIndex, startInChannel);
  
  return maxCopyLength;
},

/**
* 验证copyToChannel是否成功写入数据
* @param {AudioBuffer} audioBuffer - 音频缓冲区
* @param {number} channelIndex - 声道索引
* @param {Float32Array} sourceArray - 原始源数据数组
* @param {number} [startInChannel=0] - 写入的起始位置
* @returns {Object} 验证结果
*/
verifyCopyToChannel(audioBuffer, channelIndex, sourceArray, startInChannel = 0) {
  // 基本参数验证
  // if (!(audioBuffer instanceof AudioBuffer)) {
  //     return { success: false, message: '无效的AudioBuffer实例' };
  // }

  // 获取目标声道数据
  const targetData = audioBuffer.getChannelData(channelIndex);
  const maxCheckLength = Math.min(
      sourceArray.length, 
      targetData.length - startInChannel
  );

  // 检查不匹配项
  const mismatches = [];
  const sampleTolerance = 1e-6;

  for (let i = 0; i < maxCheckLength; i++) {
      const sourceValue = sourceArray[i];
      const targetValue = targetData[startInChannel + i];
      
      if (Math.abs(sourceValue - targetValue) > sampleTolerance) {
          mismatches.push({
              position: i,
              sourceValue,
              targetValue,
              difference: Math.abs(sourceValue - targetValue)
          });
          
          if (mismatches.length >= 10) break;
      }
  }

  // 返回验证结果
  if (mismatches.length === 0) {
      return {
          success: true,
          message: `数据成功写入，验证了 ${maxCheckLength} 个样本`,
          details: { checkedSamples: maxCheckLength }
      };
  } else {
      return {
          success: false,
          message: `写入验证失败，发现 ${mismatches.length} 处不匹配`,
          details: { mismatches }
      };
  }
},
choose1() {  
  const audioCtx = wx.createWebAudioContext()
  wx.request({
    url: 'https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/music/audio.mp3', // 音频 url
    responseType: 'arraybuffer',
    success: res => {
      audioCtx.decodeAudioData(res.data, audioBuffer => {
        const channels = audioBuffer.numberOfChannels;
        const frameCount = audioCtx.sampleRate * 2.0;
        const anotherArray = new Float32Array(frameCount);
        const rate = audioBuffer.sampleRate
        const startOffset = 0
        const endOffset = rate * 3;
        const newAudioBuffer = audioCtx.createBuffer(channels,endOffset - startOffset,rate)
        const offset = 0
        // for (let channel = 0; channel < channels; channel++) {
        //  audioBuffer.copyFromChannel(anotherArray, channel, startOffset);
        //  newAudioBuffer.copyToChannel(anotherArray, channel, offset);
        // }
         // 2. 使用copyToChannel写入左声道（索引0）
      const writtenLength = this.copyToAudioChannel(audioBuffer, 0, anotherArray, 5000); // 从位置5000开始写入
      console.log(`写入了 ${writtenLength} 个样本到左声道`);
      
      // 验证写入结果
      const writeVerification = this.verifyCopyToChannel(audioBuffer, 0, anotherArray, 5000);
      console.log('写入验证结果:', writeVerification);
      this.setData({
        result: writeVerification
      })
      }, err => {
        console.error('decodeAudioData fail', err)
      })
    }
  })
},
})